<?php
/**
 * Created by PhpStorm.
 * Script Name: Minitemplate.php
 * Create: 2023/2/7 17:54
 * Description:
 * Author: fudaoji<fdj@kuryun.cn>
 */

namespace plugin\wechat\app\admin\controller;

use plugin\wechat\app\model\MiniTemplate as TemplateM;
use plugin\wechat\app\AdminController;
use Support\Request;
use plugin\wechat\app\service\MiniTemplate as TemplateService;
use plugin\wechat\app\service\OpenPlatform;

class Minitemplate extends AdminController
{

    /**
     * @var TemplateM
     */
    protected $model;

    public function __construct()
    {
        parent::__construct(); // TODO: Change the autogenerated stub
        $this->model = new TemplateM();
    }

    private static function tabList(){
        return [
            'index' => [
                'title' => '模板库',
                'href' => url('index')
            ],
            'draft' => [
                'title' => '草稿箱',
                'href' => url('draft')
            ]
        ];
    }

    /**
     * 模板库
     * @param Request $request
     * @return mixed|\support\Response
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * Author: fudaoji<fdj@kuryun.cn>
     */
    public function index(Request $request){
        if (request()->isPost()) {
            $post_data = input('post.');
            $where = [
                ['type', '=', 1]
            ];

            $query = $this->model->where($where);
            $total = $query->count();
            if ($total) {
                $list = $query->page($post_data['page'], $post_data['limit'])
                    ->order('id', 'desc')
                    ->select();
            } else {
                $list = [];
            }
            return $this->success('success', '', ['total' => $total, 'list' => $list]);
        }

        $builder = new ListBuilder();
        $builder->setTabNav($this->tabList(), __FUNCTION__)
            ->addTopButton('self', ['text' => '同步模板库', 'class' => 'layui-btn-normal','href' => url('syncPost'),'data-ajax' => true, 'data-confirm' => true])
            ->addTableColumn(['title' => 'templateID', 'field' => 'template_id', 'minWidth' => 100])
            ->addTableColumn(['title' => '版本号', 'field' => 'user_version', 'minWidth' => 100])
            ->addTableColumn(['title' => '描述', 'field' => 'user_desc', 'minWidth' => 200])
            ->addTableColumn(['title' => '添加到模板库时间	', 'field' => 'upload_time','type'=>'datetime', 'minWidth' => 180])
            ->addTableColumn(['title' => '操作', 'minWidth' => 100, 'type' => 'toolbar'])
            ->addRightButton('delete', ['href' => url('delTemplatePost', ['template_id' => '__data_template_id__'])]);

        return $builder->show();
    }

    /**
     * 草稿箱
     * @param Request $request
     * @return mixed|\support\Response
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * Author: fudaoji<fdj@kuryun.cn>
     */
    public function draft(Request $request){
        if (request()->isPost()) {
            $post_data = input('post.');
            $where = [
                ['type', '=', 2]
            ];

            $query = $this->model->where($where);
            $total = $query->count();
            if ($total) {
                $list = $query->page($post_data['page'], $post_data['limit'])
                    ->order('id', 'desc')
                    ->select();
            } else {
                $list = [];
            }
            return $this->success('success', '', ['total' => $total, 'list' => $list]);
        }

        $builder = new ListBuilder();
        $builder->setTabNav($this->tabList(), __FUNCTION__)
            ->addTopButton('self', ['text' => '同步草稿箱', 'class' => 'layui-btn-normal','href' => url('syncDraftPost'),'data-ajax' => true, 'data-confirm' => true])
            ->addTableColumn(['title' => 'templateID', 'field' => 'template_id', 'minWidth' => 100])
            ->addTableColumn(['title' => '版本号', 'field' => 'user_version', 'minWidth' => 100])
            ->addTableColumn(['title' => '描述', 'field' => 'user_desc', 'minWidth' => 200])
            ->addTableColumn(['title' => '添加到模板库时间	', 'field' => 'upload_time','type'=>'datetime', 'minWidth' => 180])
            ->addTableColumn(['title' => '操作', 'minWidth' => 100, 'type' => 'toolbar'])
            ->addRightButton('delete', ['text' => '设为模板', 'class' => 'layui-btn-normal','href' => url('addToTemplatePost', ['template_id' => '__data_template_id__'])]);

        return $builder->show();
    }

    /**
     * 删除模板
     * @return \support\Response
     * @throws \think\db\exception\DbException
     * Author: fudaoji<fdj@kuryun.cn>
     */
    public function delTemplatePost(){
        if(request()->isPost()) {
            $template_id = input('template_id');
            if (is_string($response = TemplateService::delete(['template_id' => $template_id]))) {
                return $this->error($response);
            } else {
                $this->model->where([
                    ['type','=', 1],
                    ['template_id','=', $template_id]
                ])
                    ->delete();
                return $this->success('操作成功!');
            }
        }
    }

    /**
     * 添加草稿到模板库
     * @return \support\Response
     * @throws \Exception
     * Author: fudaoji<fdj@kuryun.cn>
     */
    public function addToTemplatePost(){
        if(request()->isPost()) {
            $template_id = input('template_id');
            if (is_string($response = TemplateService::draftToTemplate(['template_id' => $template_id]))) {
                return $this->error($response);
            } else {
                $this->syncPost();
                return $this->success('操作成功!');
            }
        }
    }

    /**
     * 同步模板
     * @return \support\Response
     * @throws \think\db\exception\DbException
     * Author: fudaoji<fdj@kuryun.cn>
     */
    public function syncPost(){
        $response = TemplateService::syncTemplate();
        if(is_string($response)) {
            return $this->error($response);
        }else{
            $list = $response['template_list'];
            $insert_data = [];
            $ids = [];
            $db_ids = $this->model->where('type', 1)
                ->column('template_id');

            //微信服务器数据与库中数据比较，新数据入库
            foreach ($list as $vo) {
                if(! in_array($vo['template_id'], $db_ids)) {
                    $temp = [
                        'template_id'      => $vo['template_id'],
                        'user_desc'     => $vo['user_desc'],
                        'user_version'  => $vo['user_version'],
                        'upload_time'   => $vo['create_time'],
                        'type'          => 1,
                        'source_miniprogram_appid' => $vo['source_miniprogram_appid'],
                        'source_miniprogram' => $vo['source_miniprogram'],
                        'developer' => $vo['developer']
                    ];
                    array_push($insert_data, $temp);
                }
                $ids[] = $vo['template_id'];
            }

            !empty($insert_data) && $this->model->saveAll($insert_data);

            //库中数据与微信服务器数据比较，不存在的删除
            $del_id = array_diff($db_ids, $ids);
            count($del_id) && $this->model->where([
                ['template_id', 'in', $del_id],
                ['type','=', 1]
            ])->delete();
        }
        return $this->success('操作成功!');
    }

    /**
     * 同步草稿箱
     * @return \support\Response
     * @throws \think\db\exception\DbException
     * Author: fudaoji<fdj@kuryun.cn>
     */
    public function syncDraftPost(){
        if(request()->isPost()) {
            $response = TemplateService::syncDraft();
            if (is_string($response)) {
                return $this->error($response);
            } else {
                $list = $response['draft_list'];
                $insert_data = [];
                $draft_ids = [];
                $db_ids = $this->model->where('type', 2)
                    ->column('template_id');

                //微信服务器数据与库中数据比较，新数据入库
                foreach ($list as $vo) {
                    if (!in_array($vo['draft_id'], $db_ids)) {
                        $temp = [
                            'template_id' => $vo['draft_id'],
                            'user_desc' => $vo['user_desc'],
                            'user_version' => $vo['user_version'],
                            'upload_time' => $vo['create_time'],
                            'type' => 2,
                            'source_miniprogram_appid' => $vo['source_miniprogram_appid'],
                            'source_miniprogram' => $vo['source_miniprogram'],
                            'developer' => $vo['developer']
                        ];
                        array_push($insert_data, $temp);
                    }
                    $draft_ids[] = $vo['draft_id'];
                }

                !empty($insert_data) && $this->model->saveAll($insert_data);

                //库中数据与微信服务器数据比较，不存在的删除
                $del_id = array_diff($db_ids, $draft_ids);
                count($del_id) && $this->model->where([
                    ['template_id', 'in', $del_id],
                    ['type','=', 2]
                ])->delete();
            }
        }
        return $this->success('操作成功!');
    }
}